package com.mnnu.aop;

import com.alibaba.fastjson.JSONObject;
import com.mnnu.mapper.OperateLogMapper;
import com.mnnu.pojo.OperateLog;
import com.mnnu.pojo.Result;
import com.mnnu.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;

import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Component
@Aspect
@Slf4j
public class OperateLogAOP {

    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private JwtUtils jwtUtils;

    @Pointcut("@annotation(com.mnnu.anno.OperateAnnotation)")
    private void pt() {}

    @Around("pt()")
    public Object recordOperateLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 创建操作日志实体对象
        OperateLog operateLog = new OperateLog();
        // 获取请求头中jwt令牌，解析得到当前操作用户id
        String jwt = httpServletRequest.getHeader("token");
        List<String> info = jwtUtils.parseJwt(jwt);
        Integer operateUser = Integer.valueOf(info.get(0));

        // 实体对象赋值
        operateLog.setOperateUser(operateUser);
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));

        // 执行目标方法，记录执行时长
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        long duration = end - begin;

        // 实体对象赋值
        operateLog.setReturnValue(JSONObject.toJSONString(result));
        operateLog.setCostTime(BigInteger.valueOf(duration));

        // 将对象存入数据库
        operateLogMapper.insert(operateLog);

        return result;
    }
}
